package com.sx.manage.interceptor;

import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * sql 关键字检测拦截器
 * 
 * @author 139570
 *
 */
public class MSqlCheckInterceptor implements HandlerInterceptor {
	private static String inj_str = "and|insert|select|delete|update";
	private Logger _log = LoggerFactory.getLogger(this.getClass());
	@Autowired
	protected HttpSession session;

	@Autowired
	protected HttpServletRequest request;

	@Autowired
	protected HttpServletResponse response;

	@SuppressWarnings("unchecked")
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object arg2) throws Exception {
	
		Iterator<String[]> values = request.getParameterMap().values().iterator();// 获取所有的表单参数
		while (values.hasNext()) {
			String[] value = values.next();
			for (int i = 0; i < value.length; i++) {
				if (sql_inj(value[i])) {
					// TODO这里发现sql注入代码的业务逻辑代码
					_log.info("发现sql注入，抛出异常");
					// throw new MSQLException("fms.sql.inject");
				}
			}
		}
		return true;
	}

	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}

	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
	}

	// 判断参数中是否包含sql关键字
	public boolean sql_inj(String str) {
		String[] inj_stra = inj_str.split("\\|");
		for (int i = 0; i < inj_stra.length; i++) {
			if (str.indexOf(" " + inj_stra[i] + " ") >= 0) {
				_log.info("参数：" + str + ":被认为是sql注入,关键字:" + inj_stra[i]);
				return true;
			}
		}
		return false;
	}
}
